import 'dart:io';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_core_widget/widgets/image/oss_image_provider.dart';
import 'package:kq_flutter_core_widget/widgets/imageBox/kq_image_box.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

import '../../../config/kq_global.dart';
import '../../../resources/images.dart';
import '../../../resources/kq_theme_colors.dart';
import '../../../widgets/indicator/kq_page_indicator.dart';

/// 图片预览界面
class ImgPreviewPage extends StatefulWidget {
  const ImgPreviewPage({super.key});

  @override
  ImgPreviewPageState createState() => ImgPreviewPageState();
}

class ImgPreviewPageState extends State<ImgPreviewPage> {
  late List<ImageUrl> imageUrls;
  int position = 0;
  PageController? pageController;

  @override
  void initState() {
    super.initState();
    imageUrls = Get.arguments;
    var params = Get.parameters;
    position = int.parse(params['position'] ?? '0');
    pageController = PageController(initialPage: position);
  }

  _buildProvider(ImageUrl imageUrl) {
    switch (imageUrl.imageType) {
      case ImageType.file:
        return FileImage(File(imageUrl.url));
      case ImageType.http:
        return NetworkImage(imageUrl.url);
      case ImageType.oss:
        if (imageUrl.url.startsWith("http")) {
          return NetworkImage(imageUrl.url);
        }
        return OSSImageProvider(imageUrl.url);
      case ImageType.assets:
        return AssetImage(imageUrl.url);
    }
  }

  @override
  void didUpdateWidget(covariant ImgPreviewPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    imageUrls = Get.arguments;
    var params = Get.parameters;
    position = int.parse(params['position'] ?? '0');
    pageController = PageController(initialPage: position);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Column(
        children: [
          // 标题
          Row(
            children: [
              Expanded(
                child: Stack(
                  children: [
                    Container(
                      color: KqThemeColors.bgBlue,
                      height: 55.r,
                      child: Row(
                        children: [
                          KqInkWell(
                            verticalPadding: 15.5.r,
                            horizontalPadding: 32.r,
                            onTap: Get.back,
                            child: Image.asset(
                              Images.commonBack,
                              width: 24.r,
                              height: 24.r,
                              package: KqGlobal.packageName,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Positioned(
                      left: 0,
                      right: 0,
                      top: 0,
                      bottom: 0,
                      child: DefaultTextStyle(
                        style: TextStyle(
                          color: KqThemeColors.textWhite,
                          fontSize: 24.sp,
                        ),
                        child: Container(
                          alignment: Alignment.center,
                          child: Text('${position + 1}/${imageUrls.length}'),
                        ),
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
          Expanded(
              child: Stack(
            children: [
              PhotoViewGallery.builder(
                scrollPhysics: const BouncingScrollPhysics(),
                builder: (BuildContext context, int index) {
                  var imageUrl = imageUrls[index];
                  return PhotoViewGalleryPageOptions(
                    imageProvider: _buildProvider(imageUrl),
                    initialScale: PhotoViewComputedScale.contained * 1.0,
                    heroAttributes: PhotoViewHeroAttributes(
                      tag: imageUrl.url,
                    ),
                    errorBuilder: (context, error, stackTrace) {
                      return Image.asset(Images.commonPicQuesheng1024,
                          package: KqGlobal.packageName, fit: BoxFit.contain);
                    },
                  );
                },
                pageController: pageController,
                itemCount: imageUrls.length,
                onPageChanged: (index) {
                  setState(() {
                    position = index;
                  });
                },
                loadingBuilder: (context, event) => Center(
                  child: event == null || event.expectedTotalBytes == null
                      ? SizedBox(
                          width: 50.r,
                          height: 50.r,
                          child: const CircularProgressIndicator(),
                        )
                      : SizedBox(
                          width: 20.r,
                          height: 20.r,
                          child: CircularProgressIndicator(
                            value: event.cumulativeBytesLoaded /
                                event.expectedTotalBytes!,
                          ),
                        ),
                ),
              ),
              if (imageUrls.length > 1 && position > 0)
                Positioned(
                    left: 48.r,
                    top: 0,
                    bottom: 0,
                    child: Align(
                      alignment: Alignment.center,
                      child: KqInkWell(
                        backgroundColor: Colors.white.withOpacity(0.35),
                        radius: 100.r,
                        onTap: () {
                          if (position > 0) {
                            pageController?.jumpToPage(position - 1);
                          }
                        },
                        child: SizedBox(
                          width: 72.r,
                          height: 72.r,
                          child: Icon(
                            Icons.keyboard_arrow_left,
                            size: 45.r,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    )),
              if (imageUrls.length > 1 && position < imageUrls.length - 1)
                Positioned(
                    right: 48.r,
                    top: 0,
                    bottom: 0,
                    child: Align(
                      alignment: Alignment.center,
                      child: KqInkWell(
                        backgroundColor: Colors.white.withOpacity(0.35),
                        radius: 100.r,
                        onTap: () {
                          if (position < imageUrls.length - 1) {
                            pageController?.jumpToPage(position + 1);
                          }
                        },
                        child: SizedBox(
                          width: 72.r,
                          height: 72.r,
                          child: Icon(
                            Icons.keyboard_arrow_right,
                            size: 45.r,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    )),
              Positioned(
                  left: 0,
                  right: 0,
                  bottom: 88.r + KqScreenUtil().bottomBarHeight,
                  child: KqPageIndicator(
                    index: position,
                    count: imageUrls.length,
                  ))
            ],
          ))
        ],
      ),
    );
  }
}
